package com.mine.async.jobexe;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.function.Function;

@Slf4j
@Component("downloadJobExecutorSimple")
public class DownloadJobExecutorSimple extends DownloadJobExecutor {

    @Resource
    private TaskExecutor taskExecutor;

    @Resource
    private DownloadJobHandler downloadJobHandler;

    @Override
    public String createJob(Selector selector, PageQuery pageQuery) {
        String jobNo = downloadJobHandler.createInitJob(pageQuery);
        taskExecutor.execute(() -> super.executeJob(jobNo, p -> this.pageToRespDTO(selector.select()), pageQuery));
        return jobNo;
    }

    @Override
    public String createJob(Function<PageQuery, Page> function, PageQuery pageQuery) {
        String jobNo = downloadJobHandler.createInitJob(pageQuery);
        taskExecutor.execute(() -> super.executeJob(jobNo, p -> this.pageToRespDTO(function.apply(p)), pageQuery));
        return jobNo;
    }

    @Override
    public String createJobGitHub(Function<PageQuery, PageRespBase> function, PageQuery pageQuery) {
        String jobNo = downloadJobHandler.createInitJob(pageQuery);
        taskExecutor.execute(() -> super.executeJob(jobNo, p -> this.pageToRespDTO(function.apply(p)), pageQuery));
        return jobNo;
    }

    @Override
    public DownloadJobHandler getDownloadJobHandler() {
        return downloadJobHandler;
    }

    private PageRespDTO pageToRespDTO(Page page) {
        return page == null
                ?
                PageRespDTO.builder().build()
                :
                PageRespDTO.builder()
                        .current(page.getCurrent())
                        .size(page.getSize())
                        .total(page.getTotal())
                        .records(page.getRecords())
                        .build();
    }

    private PageRespDTO pageToRespDTO(PageRespBase page) {
        return page == null
                ?
                PageRespDTO.builder().build()
                :
                PageRespDTO.builder()
                        .current(page.getCurrPage())
                        .size(page.getPageSize())
                        .total(page.getTotalCount())
                        .records(page.getList())
                        .build();
    }

}

